package com.dgut.service.impl;

import com.dgut.Config.AppProperties;
import com.dgut.service.TokenService;
import com.dgut.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    AppProperties appProperties;
    @Autowired
    JwtUtil jwtUtil;

    @Override
    public String createAccessToken(User user) {
        return jwtUtil.createAccessToken(user);
    }

    @Override
    public String getAccessToken(HttpServletRequest request) {
        String authenticationHeader = request.getHeader(appProperties.getJwt().getHeader());
        try{
            String accessToken = authenticationHeader.substring(appProperties.getJwt().getPrefix().length(), authenticationHeader.length());
            return accessToken;
        } catch (Exception e){
            return null;
        }

    }

    @Override
    public Optional<Claims> getUserByAccessToken(String accessToken) {
        jwtUtil.parseClaims(accessToken, jwtUtil.getKey());
        return jwtUtil.parseClaims(accessToken, jwtUtil.getKey());
    }

    @Override
    public String getUserNameByAccessToken(String accessToken) {
        jwtUtil.parseClaims(accessToken, jwtUtil.getKey());
        return jwtUtil.parseClaims(accessToken, jwtUtil.getKey()).get().getSubject();
    }

    @Override
    public Boolean isAccessTokenValid(String accessToken) {
        System.out.println("isAccessTokenValid");
        System.out.println("isAccessTokenValid: " + jwtUtil.validateToken(accessToken, jwtUtil.getKey()));
        return jwtUtil.validateToken(accessToken, jwtUtil.getKey());
        //return jwtUtil.validateToken(accessToken, jwtUtil.getKey());
    }
}
